package com.itheima.tlias.aop;


import com.alibaba.fastjson.JSONObject;
import com.itheima.tlias.mapper.EmpMapper;
import com.itheima.tlias.mapper.OperateLogMapper;
import com.itheima.tlias.pojo.OperateLog;
import com.itheima.tlias.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(com.itheima.tlias.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {

        //解析令牌获取操作人ID
        String jwt = request.getHeader("token");
        Claims claim = JwtUtils.parseJWT(jwt);
        Integer operaterid = (Integer) claim.get("id");

        //获取当前操作时间
        LocalDateTime operatetime = LocalDateTime.now();

        //获取操作类名
        String classname = joinPoint.getTarget().getClass().getName();

        //获取操作方法
        String methodname = joinPoint.getSignature().getName();

        //获取操作参数
        Object[] args = joinPoint.getArgs();
        String methodParams= Arrays.toString(args);

        //记录开始执行时间
        long start = System.currentTimeMillis();

        Object result = joinPoint.proceed();

        //记录接数执行时间
        long end = System.currentTimeMillis();

        //获取返回值
        String returnvalue = JSONObject.toJSONString(result);

        //获取执行花费时间
        long costtime = end - start;

        //将所有参数构造Log对象
        OperateLog Log = new OperateLog(null,operaterid,operatetime,classname,methodname,methodParams,returnvalue,costtime);
        operateLogMapper.insert(Log);


        log.info("AOP操作日志{}",Log);
        return result;
    }


}
